<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 150px;" placeholder="请输入司机姓名"/>
      <el-date-picker
        v-model="dateRange"
        :picker-options="rangeOptions"
        class="filter-item"
        style="width: 300px;"
        align="left"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy/MM/dd"/>
      <el-button v-permission="['GET /admin/drivermgr/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/drivermgr/list']" v-if="isIEBrowser()" class="filter-item" type="primary" icon="el-icon-search" @click="readAndQuery">读卡查找</el-button>
      <el-button v-permission="['POST /admin/drivermgr/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button v-permission="['POST /admin/drivermgr/list']" class="filter-item" type="primary" icon="el-icon-printer" @click="batchPrintPDF">打印</el-button>
      <el-button v-permission="['POST /admin/drivermgr/list']" class="filter-item" type="primary" icon="el-icon-document" @click="exportData">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row @row-click="handleDetail">
      <!-- <el-table-column label="序号" type="index" align="center" show-overflow-tooltip width="50px"/> -->
      <el-table-column align="center" label="姓名" prop="name" sortable width="150px"/>
      <el-table-column :formatter="formatGender" align="center" label="性别" prop="gender" width="50px"/>
      <el-table-column align="center" label="驾驶证号" prop="driverLicense" width="200px"/>
      <el-table-column align="center" label="所属公司" prop="company"/>
      <el-table-column align="center" label="所属大队" prop="trafficPolice" />
      <el-table-column align="center" label="操作时间" prop="updateDate"/>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <!-- <el-button v-permission="['GET /admin/drivermgr/list']" type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button> -->
          <el-button v-permission="['POST /admin/drivermgr/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/drivermgr/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 创建/修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
      <el-form
        ref="dataForm"
        :rules="dialogStatus !== 'update' ? rules : updateRules"
        :model="dataForm"
        status-icon
        label-position="right"
        label-width="100px"
        style="width: 100%;margin-left:40px">
        <el-row>
          <el-col :span="16">
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="dataForm.name" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="dataForm.gender" placeholder="请选择">
                    <el-option label="男" value="1"/>
                    <el-option label="女" value="0"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="dataForm.birthday"
                    :picker-options="dateOptions"
                    value-format="yyyy/MM/dd"
                    placeholder="选择日期"
                    type="date"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名族" prop="nation">
                  <el-input v-model="dataForm.nation" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- <el-col :span="12">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model="dataForm.age"/>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="联系电话" prop="tel">
                  <el-input v-model="dataForm.tel"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="4" >
            <img v-if="dataForm.photoBase64" :src="'data:image/png;base64,' + dataForm.photoBase64" style="margin-left:20px">
            <i v-else class="el-icon-plus avatar-uploader-icon" style="margin-left:60px; margin-top:70px"/>
          </el-col>
          <el-col v-if="isIEBrowser()" :span="4" >
            <el-button @click="readCert">读卡</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="户口地址" prop="address">
              <el-input :rows="1" v-model="dataForm.address" type="textarea" placeholder="户口地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="所属公司" prop="company">
              <el-autocomplete
                v-model="dataForm.company"
                :fetch-suggestions="querySearch"
                :trigger-on-focus="false"
                style="width:100%"
                placeholder="请输入内容"
                @select="handleSelect" />
                <!-- <el-input v-model="dataForm.company" placeholder="所属公司"/> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="驾驶证号" prop="driverLicense">
              <el-input v-model="dataForm.driverLicense" placeholder="驾驶证号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属大队" prop="trafficPolice">
              <el-select v-model="dataForm.trafficPolice" placeholder="请选择">
                <el-option
                  v-for = "(item, index) in trafficPolicOptions"
                  :key = "index"
                  :label="item"
                  :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="合格证号" prop="certificateNo">
              <el-input v-model="dataForm.certificateNo" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="发证日期" prop="certificateDate">
              <el-date-picker
                v-model="dataForm.certificateDate"
                :picker-options="dateOptions"
                value-format="yyyy/MM/dd"
                placeholder="选择日期"
                type="date"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="理论考试时间" prop="theoryExaminationTime">
              <el-date-picker
                v-model="dataForm.theoryExaminationTime"
                :picker-options="dateOptions"
                value-format="yyyy/MM/dd"
                placeholder="理论考试时间"
                type="date"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="理论考试结果" prop="theoryResult">
              <el-input v-model="dataForm.theoryResult" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="理论补考时间" prop="resitTheoryExaminationTime">
              <el-date-picker
                v-model="dataForm.resitTheoryExaminationTime"
                :picker-options="dateOptions"
                value-format="yyyy/MM/dd"
                placeholder="理论补考时间"
                type="date"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="理论补考结果" prop="resitTheoryResult">
              <el-input v-model="dataForm.resitTheoryResult" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="技能考试时间" prop="skillExaminationTime">
              <el-date-picker
                v-model="dataForm.skillExaminationTime"
                :picker-options="dateOptions"
                value-format="yyyy/MM/dd"
                placeholder="技能考试时间"
                type="date"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="技能考试结果" prop="skillResult">
              <el-input v-model="dataForm.skillResult" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="技能补考时间" prop="resitSkillExaminationTime">
              <el-date-picker
                v-model="dataForm.resitSkillExaminationTime"
                :picker-options="dateOptions"
                value-format="yyyy/MM/dd"
                placeholder="技能补考时间"
                type="date"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="技能补考结果" prop="resitSkillResult">
              <el-input v-model="dataForm.resitSkillResult" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注" prop="remark">
              <el-input :rows="2" v-model="dataForm.remark" type="textarea" placeholder="输入备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogDetailVisible" title="详情" width="70%">
      <div id="printArea">
        <driver-table-info :data="dataForm"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">取消</el-button>
        <el-button type="primary" @click="printPDF">打印</el-button>
      </div>
    </el-dialog>
    <object id="CertCtl" type="application/cert-reader" width="0" height="0"/>
    <div id="batchPrintArea" style="display:none">
      <div v-for="item in list" :key="item.id" style="page-break-after:always" >
        <driver-table-info :data="item"/>
      </div>
    </div>
  </div>
</template>

<style>
    #printArea {
        overflow:auto;
        display: block;
    }
    .table_info, .table_info>tr, .table_info>tr>td {
        border:1px solid black;
    }
    .table_info>.table_footer {
        display: none;
    }

    .table_info>tr>td {
        height: 36px;
        min-width: 100px;
        max-width: 250px;
        word-wrap: break-word;
        padding-left:10px;
    }
    .el-range-input ,.el-range-separator{
      display: inline-block !important;
      vertical-align: middle !important;
      margin-bottom: 15px !important;
    }
</style>

<script>
import { downloadExcel, queryByDriverisLicense, queryAllCompany, listDriver, createDriver, updateDriver, deleteDriver } from '../../api/driver'
import { getToken } from '../../utils/auth'
import { driverTableInfo } from './driver-table-info'
import Pagination from '@/components/Pagination'
import { isLicenseExist } from '../../api/validator'

export default {
  name: 'Driver',
  components: {
    driverTableInfo,
    Pagination
  },
  data() {
    return {
      list: null,
      total: 0,
      roleOptions: null,
      listLoading: true,
      dateRange: null,
      listQuery: {
        page: 1,
        limit: 20,
        startTime: undefined,
        endTime: undefined,
        name: undefined,
        sort: 'createDate',
        order: 'desc'
      },
      trafficPolicOptions: ['南京交警一大队', '南京交警二大队', '南京交警三大队', '南京交警四大队', '南京交警五大队',
        '南京交警六大队', '南京交警七大队', '南京交警八大队', '南京交警九大队', '南京交警十大队', '溧水交警大队', '高淳交警大队'],
      dateOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      dataForm: {
        id: undefined,
        name: undefined,
        gender: undefined,
        birthday: undefined,
        nation: undefined,
        age: '1',
        address: undefined,
        tel: undefined,
        photoBase64: undefined,
        company: undefined,
        driverLicense: undefined,
        trafficPolice: undefined,
        certificateNo: undefined,
        certificateDate: undefined,
        theoryExaminationTime: undefined,
        theoryResult: undefined,
        resitTheoryExaminationTime: undefined,
        resitTheoryResult: undefined,
        skillExaminationTime: undefined,
        skillResult: undefined,
        resitSkillExaminationTime: undefined,
        resitSkillResult: undefined,
        remark: undefined
      },
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
        detail: '查看详情'
      },
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        birthday: [{ required: true, message: '生日不能为空', trigger: 'blur' }],
        nation: [{ required: true, message: '名族不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
        driverLicense: [{ required: true, message: '驾驶证号不能为空', trigger: 'blur' }, { validator: isLicenseExist, trigger: 'blur' }]
      },
      updateRules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        birthday: [{ required: true, message: '生日不能为空', trigger: 'blur' }],
        nation: [{ required: true, message: '名族不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
        driverLicense: [{ required: true, message: '驾驶证号不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      restaurants: [],
      rangeOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-RCS-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    queryAllCompany()
      .then(response => {
        this.restaurants = response.data.body
      })
  },
  methods: {
    initCompanyInfo() {
      queryAllCompany()
        .then(response => {
          this.restaurants = response.data.body
        })
    },
    getList() {
      this.listLoading = true
      // 格式化当前listQuery
      if (this.dateRange) {
        this.listQuery.startTime = this.dateRange[0]
        this.listQuery.endTime = this.dateRange[1]
      }

      listDriver(this.listQuery)
        .then(response => {
          this.list = response.data.body.dataList
          this.total = response.data.body.totalSize
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      this.initCompanyInfo()
    },
    isIEBrowser() {
      if (!!window.ActiveXObject || 'ActiveXObject' in window) {
        return true
      } else {
        return false
      }
    },
    readAndQuery() {
      this.doReadCert((result) => {
        if (!result) {
          return
        }
        queryByDriverisLicense(result.certNumber)
          .then(response => {
            // 读取到数据，是否进行展示
            this.$confirm('信息已经存在，编辑数据还是查看数据详情？', '提示', {
              confirmButtonText: '编辑',
              cancelButtonText: '详情',
              type: 'info'
            }).then(() => {
              // 打开编辑页面
              this.handleUpdate(response.data.body)
            }).catch(() => {
              this.showDetailDiagle(response.data.body)
            })
          })
          .catch(response => {
            this.$confirm('信息不存在，是否需要创建？', '提示', {
              confirmButtonText: '创建',
              cancelButtonText: '取消',
              type: 'info'
            }).then(() => {
              // 打开创建页面
              this.handleCreate()
              this.updateFormVal(result)
            })
          })
      })
    },
    printPDF() {
      this.print('printArea')
    },
    batchPrintPDF() {
      this.print('batchPrintArea')
    },
    print(id) {
      var printHtml = document.getElementById(id).innerHTML
      // 添加打印的样式
      var style = '<style type="text/css"> \n ' +
            ' body{overflow:hidden;display: block; } \n' +
            // '  table{border:1px solid #666;} \n' +
            ' td{ height:56px; word-wrap: break-word; min-width: 200px;max-width: 250px;font-size: 20px;padding-left:10px} \n' +
            '</style>'
      var wind = window.open('', 'newwindow',
        'height=300, width=700, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no')
      wind.document.head.innerHTML = style
      wind.document.body.innerHTML = printHtml
      wind.print()
      wind.close()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        gender: undefined,
        birthday: undefined,
        nation: undefined,
        age: '1',
        address: undefined,
        tel: undefined,
        photoBase64: undefined,
        company: undefined,
        driverLicense: undefined,
        trafficPolice: undefined,
        certificateNo: undefined,
        certificateDate: undefined,
        theoryExaminationTime: undefined,
        theoryResult: undefined,
        resitTheoryExaminationTime: undefined,
        resitTheoryResult: undefined,
        skillExaminationTime: undefined,
        skillResult: undefined,
        resitSkillExaminationTime: undefined,
        resitSkillResult: undefined,
        remark: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createDriver(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.body)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
              console.log('准备更新')
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errMsg
              })
            })
        }
      })
    },
    formatGender(row, column) {
      try {
        var gender = row[column.property]
        return gender === '1' ? '男' : '女'
      } catch (e) {
        console.log(e)
      }
    },
    exportData() {
      this.listQuery
      var query = Object.assign({}, this.listQuery)
      query.page = null
      query.limit = null
      query.sort = null
      query.order = null
      downloadExcel(query)
    },
    readCert() {
      this.doReadCert((result) => {
        if (result) {
          this.updateFormVal(result)
        }
      })
    },
    doReadCert(callback) {
      this.$confirm('确保读卡机处于连接状态，否则会导致卡死, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 读卡并连接
        // moniduquchengg
        // callback({
        //   nation:"汉",
        //   bornDay:"19901017",
        //   certNumber:"123123",
        //   certAddress:"江苏省南京市",
        //   partyName:"葛于波",
        //   gender:"男"
        // })
        callback(this.connectAndRead())
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    toJson(str) {
      console.log(str)
      var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
      return new Fn('return ' + '(' + str + ')')()
    },
    connectAndRead() {
      var CertCtl = document.getElementById('CertCtl')
      try {
        console.log('准备链接')
        var result = this.toJson(CertCtl.connect())
        if (result.resultFlag !== 0) {
          this.$notify.error({
            title: '失败',
            message: result.errorMsg
          })
          return
        }
        // 读取数据
        result = this.toJson(CertCtl.readCert())
        if (result.resultFlag !== 0) {
          this.$notify.error({
            title: '失败',
            message: result.errorMsg
          })
          return
        }
        return result.resultContent
      } catch (e) {
        console.log(e)
        this.$message({
          type: '失败',
          message: '读取失败'
        })
      } finally {
        CertCtl.disconnect()
      }
    },
    updateFormVal(formInfo) {
      this.dataForm.name = formInfo.partyName
      if (formInfo.gender === '男' || formInfo.gender === 1) {
        this.dataForm.gender = '1'
      } else {
        this.dataForm.gender = '0'
      }
      this.dataForm.nation = formInfo.nation
      this.dataForm.birthday = formInfo.bornDay
      this.dataForm.address = formInfo.certAddress
      this.dataForm.driverLicense = formInfo.certNumber
      this.dataForm.photoBase64 = formInfo.identityPic
      var bornDay = formInfo.bornDay
      if (bornDay && bornDay.length === 8) {
        var year = bornDay.substring(0, 4)
        var month = bornDay.substring(4, 6)
        var day = bornDay.substring(6, 8)
        this.dataForm.birthday = year + '/' + month + '/' + day
        var dateTime = new Date()
        var currentYear = dateTime.getFullYear()
        this.dataForm.age = currentYear - parseInt(year)
      }
    },
    handleDetail(row, column, event) {
      if (row[column.property]) {
        this.showDetailDiagle(row)
      }
    },
    showDetailDiagle(data) {
      this.dataForm = Object.assign({}, data)
      this.dialogDetailVisible = true
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateDriver(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
              console.log('准备更新')
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errMsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteDriver({ id: row.id })
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          console.log('准备更新')
          this.getList()
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errMsg
          })
        })
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      if (restaurants && restaurants.length !== 0) {
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      } else {
        cb(restaurants)
      }
    },
    createFilter(queryString) {
      return (restaurant) => {
        return !restaurant || (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1)
      }
    },
    handleSelect(item) {
      console.log(item)
    }
  }
}
</script>
